package com.hangzhou.welbeing.welbeinginstrument.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.BindingMobileBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.VerificationCodeBean;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 29.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.welbeinginstrument.activity
 * 工程名 welbeing_pregnant
 */
public class BindingMobilePhoneNumberActivity extends Activity {
    private static final String TAG = "BindingMobilePhoneNumberActivity";
    @Bind(R.id.activity_binding_mobile_phone_number_iv_return)
    ImageView activityBindingMobilePhoneNumberIvReturn;
    @Bind(R.id.activity_binding_mobile_phone_number_et_Enter_phone_number)
    EditText activityBindingMobilePhoneNumberEtEnterPhoneNumber;
    @Bind(R.id.activity_binding_mobile_phone_number_et_Input_validation_code)
    EditText activityBindingMobilePhoneNumberEtInputValidationCode;
    @Bind(R.id.activity_binding_mobile_phone_number_tv_Get_verification_code)
    TextView activityBindingMobilePhoneNumberTvGetVerificationCode;
    @Bind(R.id.activity_binding_mobile_phone_number_et_Enter_password)
    EditText activityBindingMobilePhoneNumberEtEnterPassword;
    @Bind(R.id.activity_binding_mobile_phone_number_bt_determine)
    Button activityBindingMobilePhoneNumberBtDetermine;

    private String id;
    private String userNAME;

    private int i = RBConstants.COUNTDOWN;
    private Timer timer = null;
    private TimerTask task = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binding_mobile_phone_number);
        ButterKnife.bind(this);

        Utils.setStatusBar(this, false, false);
        Utils.setStatusTextColor(true, this);
        Intent intent = getIntent();
        id = intent.getStringExtra("ID");
        userNAME = intent.getStringExtra("userNAME");
    }

    @OnClick({R.id.activity_binding_mobile_phone_number_iv_return,
            R.id.activity_binding_mobile_phone_number_bt_determine,
            R.id.activity_binding_mobile_phone_number_tv_Get_verification_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_binding_mobile_phone_number_iv_return:
                finish();
                break;
            case R.id.activity_binding_mobile_phone_number_bt_determine:
                String phone_number = activityBindingMobilePhoneNumberEtEnterPhoneNumber.getText().toString().trim();
                if (!TextUtils.isEmpty(phone_number)) {
                    String validation_code = activityBindingMobilePhoneNumberEtInputValidationCode.getText().toString().trim();
                    if (!TextUtils.isEmpty(validation_code)) {
                        String enter_password = activityBindingMobilePhoneNumberEtEnterPassword.getText().toString().trim();
                        if (!TextUtils.isEmpty(enter_password)) {
                            submitBindingMobilePhoneNumber(phone_number, validation_code, enter_password);
                        } else {
                            Toast.makeText(BindingMobilePhoneNumberActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(BindingMobilePhoneNumberActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(BindingMobilePhoneNumberActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.activity_binding_mobile_phone_number_tv_Get_verification_code:
                String trim = activityBindingMobilePhoneNumberTvGetVerificationCode.getText().toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    verificationcode(trim);
                    startTime();
                } else {
                    Toast.makeText(BindingMobilePhoneNumberActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * @param
     * @desc 提交绑定手机号
     */
    private void submitBindingMobilePhoneNumber(String phone_number, String validation_code, String enter_password) {
        SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id", "");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL)
                .addParams(userNAME, id)
                .addParams("tel", phone_number)
                .addParams("password", enter_password)
                .addParams("code", validation_code)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Log.e(TAG, "string+++--------------------+》" + stringparseNetworkResponse);
                        Gson gson = new Gson();
                        final BindingMobileBean bindingMobileBean = gson.fromJson(stringparseNetworkResponse, BindingMobileBean.class);
                        if (bindingMobileBean.errorCode == 200) {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(NewRegisteredActivity.this,"验证码已经发送",Toast.LENGTH_SHORT).show();
                                    Toast.makeText(BindingMobilePhoneNumberActivity.this, bindingMobileBean.errorMessage, Toast.LENGTH_SHORT).show();

                                    SharedPreferences sp = getSharedPreferences("second_app_internal_data", 0);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("user_id", bindingMobileBean.data.id);
                                    edit.putString("token",bindingMobileBean.data.token);
                                    edit.putBoolean("is_login", true);
                                    edit.commit();
                                    Intent intent2 = new Intent(BindingMobilePhoneNumberActivity.this, MainActivity.class);
                                    startActivity(intent2);
                                }
                            });
                        } else {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(NewRegisteredActivity.this,"验证码已经发送",Toast.LENGTH_SHORT).show();
                                    Toast.makeText(BindingMobilePhoneNumberActivity.this, bindingMobileBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }

    /**
     * @param trim
     * @desc 获取验证码
     */
    private void verificationcode(String trim) {
        OkHttpUtils
                .get()
                .url(RBConstants.SERVER_URL + RBConstants.SERVER_SENDDUANXIN_URL)
                .addParams("tel", trim)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String stringparseNetworkResponse = response.body().string();
                        Log.e(TAG, "string+++--------------------+》" + stringparseNetworkResponse);
                        Gson gson = new Gson();
                        final VerificationCodeBean verificationCodeBean = gson.fromJson(stringparseNetworkResponse, VerificationCodeBean.class);
                        if (verificationCodeBean.errorCode == 200 && verificationCodeBean.errorMessage.equals("OK")) {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(NewRegisteredActivity.this,"验证码已经发送",Toast.LENGTH_SHORT).show();
                                    Toast.makeText(BindingMobilePhoneNumberActivity.this, "验证码已经发送,注意查看", Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //Toast.makeText(NewRegisteredActivity.this,"验证码已经发送",Toast.LENGTH_SHORT).show();
                                    Toast.makeText(BindingMobilePhoneNumberActivity.this, verificationCodeBean.errorMessage, Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (i > 0) {
                activityBindingMobilePhoneNumberTvGetVerificationCode.setText("重新发送" + i + "s");
                startTime();
            } else {
                stopTime();
                activityBindingMobilePhoneNumberTvGetVerificationCode.setText("获取验证码");
                i = 60;
            }
        }
    };

    public void startTime() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                i--;
                Message message = mHandler.obtainMessage();
                message.arg1 = i;
                mHandler.sendMessage(message);
            }
        };
        timer.schedule(task, 1000);
    }

    public void stopTime() {
        timer.cancel();
    }

    /**
     * 验证是否是手机号码
     *
     * @param str
     * @return
     */
    public static boolean isMobile(String str) {
        Pattern pattern = Pattern.compile("1[0-9]{10}");
        Matcher matcher = pattern.matcher(str);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }
}
